<?php

#<editor-fold defaultstate="collapsed" desc="CCore::Using">
CCore::Using('labs.pop3server');
CCore::Using('socket.inc.streams.inc.interface');
#</editor-fold>

class CCoreSocketIncStreamsPop3Server implements ICoreSocketIncStreams
{
	#<editor-fold defaultstate="collapsed" desc="private">
	/**
	 * @var	CCoreLabsPop3Server
	 */
	private $_oPop3Server;

	/**
	 * @var	array
	 */
	private $_aCurrentResult;

	/**
	 * @var	int
	 */
	private $_iCurrentResultIndex;

	/**
	 * @var	bool
	 */
	private $_bIsConnected;
	#</editor-fold>

	/**
	 * @param	string	$sStreamData
	 * @return	CCoreSocketIncStreamsPop3Server
	 */
	public function __construct($sStreamData)
	{
		CCore::CheckTypes(array('$sStreamData'));

		$this->_oPop3Server = new CCoreLabsPop3Server($sStreamData);
		$this->_aCurrentResult = array();
		$this->_iCurrentResultIndex = 0;
		$this->_bIsConnected = false;
	}

	/**
	 * @param	string	$sHost
	 * @param	int		$iPort
	 * @param	int		&$iErrorNo
	 * @param	string	&$sErrorStr
	 * @param	int		$iConnectTimeOut
	 * @return	bool
	 */
	public function Open($sHost, $iPort, &$iErrorNo, &$sErrorStr, $iConnectTimeOut)
	{
		CCore::CheckTypes(array('$sHost', '$iPort', '$iErrorNo', '$sErrorStr', '$iConnectTimeOut'));
		
		$this->_bIsConnected = true;
		$this->Write('');
		return $this->IsConnected();
	}

	/**
	 * @return	void
	 */
	public function Close()
	{
		$this->_aCurrentResult = array();
		$this->_iCurrentResultIndex = 0;
		$this->_bIsConnected = false;
		return true;
	}

	/**
	 * @return	bool
	 */
	public function IsConnected()
	{
		return $this->_bIsConnected;
	}

	/**
	 * @param	string	$sLine
	 * @return	bool
	 */
	public function Write($sLine)
	{
		CCore::CheckTypes(array('$sLine'));

		$this->_iCurrentResultIndex = 0;
		$this->_aCurrentResult = explode("\n", $this->_getResultFromPop3Server($sLine));
		return true;
	}

	/**
	 * @return	string | false
	 */
	public function Read()
	{
		if (isset($this->_aCurrentResult[$this->_iCurrentResultIndex]))
		{
			return $this->_aCurrentResult[$this->_iCurrentResultIndex++]."\n";
		}
		return false;
	}

	/**
	 * @return	array | false
	 */
	public function Status()
	{
		return array();
	}

	/**
	 * @param	int		$iSocketTimeOut
	 * @param	bool	$bSocketBlocking
	 */
	public function SetTimeAndBlocking($iSocketTimeOut, $bSocketBlocking)
	{
		CCore::CheckTypes(array('$iSocketTimeOut', '$bSocketBlocking'));
	}

	/**
	 * @param	string	$sLine
	 * @return	string
	 */
	private function _getResultFromPop3Server($sLine)
	{
		CCore::CheckTypes(array('$sLine'));
		
		return $this->_oPop3Server->Response($sLine);
	}
}